﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using entity;
using System.Text;
using cmsservice.BLL;
using cmsservice.Common;

/// <summary>
///NewsListBLL 的摘要说明
/// </summary>
public class NewsListBLL
{
    public NewsListBLL()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    public string GetTypeList(string typeId, int count = 500)
    {
        if (typeId.ToUpper() == "A0305")
        {
            NewStockTPBLL bll = new NewStockTPBLL();
            return bll.GetList(count);
        }
        else
        {
            string key = "typeId:" + typeId + "_" + count.ToString();
            string str = (string)MemcachedTools.Get(key);
            if (!string.IsNullOrEmpty(str))
            {
                return str;
            }
            if (string.IsNullOrEmpty(typeId))
            {
                return "";
            }
            var db = DBManager.GetDB();

            var newsData = (from c in db.News_Type
                            join b in db.News on c.NewsId equals b.id
                            where b.IsEnable == true && c.NewsTypeId == typeId && b.ptime <= DateTime.Now && b.ptime != null
                            orderby b.ptime descending
                            select new entity.NewsList { Id = b.id, ImageUrl = b.ImageUrl, Source = b.Source, PTime = b.ptime, Step = b.step, Title = b.title, Url = b.OutsideUrl, Nature = b.Nature, Summary = b.Summary, KeyWord=b.keyword }
                       ).Take(count);
            string typeName = string.Empty;
            if (db.NewsType.Any(x => x.id == typeId))
            {
                typeName = db.NewsType.Where(x => x.id == typeId).Select(x => x.name).First();
            }

            var templist = newsData.ToList();
            var list = new List<entity.NewsList>();
            if (templist.Count > 0)
            {
                for (DateTime cdate = templist[0].PTime.Value.Date; cdate >= templist[templist.Count - 1].PTime.Value.Date; cdate = cdate.AddDays(-1))
                {
                    var temp = templist.Where(x => x.PTime.Value.Date == cdate).ToArray();
                    var temp1 = from c in temp
                                orderby c.Step descending, c.PTime descending
                                select c;
                    list.AddRange(temp1);
                }
            }
            //输出对象
            var zData = new NewsList_Lst { typename = typeName, typeid = typeId, list = list };

            str = Newtonsoft.Json.JsonConvert.SerializeObject(zData);
            MemcachedTools.Add(key, str, DateTime.Now.AddHours(1));
            return str;
        }
    }
    public string GetTypeListSummary(string typeId, int count = 50)
    {
        string key = "typeIdSummary:" + typeId + "_" + count.ToString();
        string str = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }
        if (string.IsNullOrEmpty(typeId))
        {
            return "";
        }
        var db = DBManager.GetDB();

        var newsData = (from c in db.News_Type
                        join b in db.News on c.NewsId equals b.id
                        where b.IsEnable == true && c.NewsTypeId == typeId && b.ptime <= DateTime.Now && b.ptime != null
                        orderby b.ptime descending
                        select new entity.NewsListSummary { Id = b.id, ImageUrl = b.ImageUrl, Source = b.Source, PTime = b.ptime, Step = b.step, Title = b.title, Url = b.OutsideUrl, Summary = b.Summary, KeyWord = b.keyword }
                   ).Take(count);
        string typeName = string.Empty;
        if (db.NewsType.Any(x => x.id == typeId))
        {
            typeName = db.NewsType.Where(x => x.id == typeId).Select(x => x.name).First();
        }

        var templist = newsData.ToList();
        var list = new List<entity.NewsListSummary>();
        if (templist.Count > 0)
        {
            for (DateTime cdate = templist[0].PTime.Value.Date; cdate >= templist[templist.Count - 1].PTime.Value.Date; cdate = cdate.AddDays(-1))
            {
                var temp = templist.Where(x => x.PTime.Value.Date == cdate).ToArray();
                var temp1 = from c in temp
                            orderby c.Step descending, c.PTime descending
                            select c;
                list.AddRange(temp1);
            }
        }
        //输出对象
        var zData = new NewsListSummary_Lst { typename = typeName, typeid = typeId, list = list };

        str = Newtonsoft.Json.JsonConvert.SerializeObject(zData);
        MemcachedTools.Add(key, str, DateTime.Now.AddMinutes(5));
        return str;
    }

    public string GetTypeListKeyword(string typeId, int count = 50)
    {
        string key = "typeIdKeyword:" + typeId + "_" + count.ToString();
        string str = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }
        if (string.IsNullOrEmpty(typeId))
        {
            return "";
        }
        var db = DBManager.GetDB();

        var newsData = (from c in db.News_Type
                        join b in db.News on c.NewsId equals b.id
                        where b.IsEnable == true && c.NewsTypeId == typeId && b.ptime <= DateTime.Now && b.ptime != null
                        orderby b.ptime descending
                        select new entity.NewsListSummary { Id = b.id, ImageUrl = b.ImageUrl, Source = b.Source, PTime = b.ptime, Step = b.step, Title = b.title, Url = b.OutsideUrl, Summary = b.Summary, KeyWord = b.keyword }
                   ).Take(count);
        string typeName = string.Empty;
        if (db.NewsType.Any(x => x.id == typeId))
        {
            typeName = db.NewsType.Where(x => x.id == typeId).Select(x => x.name).First();
        }

        var templist = newsData.ToList();
        var list = new List<entity.NewsListSummary>();
        if (templist.Count > 0)
        {
            for (DateTime cdate = templist[0].PTime.Value.Date; cdate >= templist[templist.Count - 1].PTime.Value.Date; cdate = cdate.AddDays(-1))
            {
                var temp = templist.Where(x => x.PTime.Value.Date == cdate).ToArray();
                var temp1 = from c in temp
                            orderby c.Step descending, c.PTime descending
                            select c;
                list.AddRange(temp1);
            }
        }
        //输出对象
        var zData = new NewsListSummary_Lst { typename = typeName, typeid = typeId, list = list };

        str = Newtonsoft.Json.JsonConvert.SerializeObject(zData);
        MemcachedTools.Add(key, str, DateTime.Now.AddMinutes(5));
        return str;
    }

    public string GetTypeList(string typeId, string keywords, int count = 50)
    {
        string key = "typeId:" + typeId + "_" + count.ToString() + "_" + keywords;
        string str = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }
        if (string.IsNullOrEmpty(typeId))
        {
            return "";
        }
        var db = DBManager.GetDB();

        var newsData = (from c in db.News_Type
                        join b in db.News on c.NewsId equals b.id
                        where b.IsEnable == true && c.NewsTypeId == typeId && b.ptime <= DateTime.Now && b.ptime != null && b.keyword.IndexOf(keywords) >= 0
                        orderby b.ptime descending
                        select new entity.NewsListSummary { Id = b.id, ImageUrl = b.ImageUrl, Source = b.Source, PTime = b.ptime, Step = b.step, Title = b.title, Url = b.OutsideUrl, Summary = b.Summary, KeyWord = b.keyword }
                   ).Take(count);
        string typeName = string.Empty;
        if (db.NewsType.Any(x => x.id == typeId))
        {
            typeName = db.NewsType.Where(x => x.id == typeId).Select(x => x.name).First();
        }

        var templist = newsData.ToList();
        var list = new List<entity.NewsListSummary>();
        if (templist.Count > 0)
        {
            for (DateTime cdate = templist[0].PTime.Value.Date; cdate >= templist[templist.Count - 1].PTime.Value.Date; cdate = cdate.AddDays(-1))
            {
                var temp = templist.Where(x => x.PTime.Value.Date == cdate).ToArray();
                var temp1 = from c in temp
                            orderby c.Step descending, c.PTime descending
                            select c;
                list.AddRange(temp1);
            }
        }
        //输出对象
        var zData = new NewsListSummary_Lst { typename = typeName, typeid = typeId, list = list };

        str = Newtonsoft.Json.JsonConvert.SerializeObject(zData);
        MemcachedTools.Add(key, str, DateTime.Now.AddHours(1));
        return str;
    }

    public string GetTypeList_xml(string typeId,int count=500)
    {
        string key = "NewsListBLL_GetTypeList_xml_typeId_"+typeId+"_count_"+count;
        string str = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }

        var db = DBManager.GetDB();
        //输出对象
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.AppendLine("<urlset>");
        var typeList = db.NewsType.Select(x => x.id).ToArray();
        var startDate = DateTime.Now.AddDays(-1);
        List<NewsList> newsData = null;
        if (!string.IsNullOrEmpty(typeId))
        {
            newsData = (from c in db.News_Type
                        join b in db.News on c.NewsId equals b.id
                        where c.NewsTypeId == typeId && b.IsEnable == true && b.ptime <= DateTime.Now
                        orderby b.ptime descending
                        select new entity.NewsList { Id = b.id, ImageUrl = b.ImageUrl, Source = b.Source, PTime = b.ptime, Step = b.step, Title = b.title, Url = b.OutsideUrl, KeyWord = b.keyword }).Take(count).ToList();
        }
        else
        { 
            newsData=(from c in db.News
                     where c.IsEnable==true && c.ptime<=DateTime.Now
                     orderby c.ptime descending
                      select new entity.NewsList { Id = c.id, ImageUrl = c.ImageUrl, Source = c.Source, PTime = c.ptime, Step = c.step, Title = c.title, Url = c.OutsideUrl, KeyWord = c.keyword }).Take(500).ToList();
        }
        var templist = newsData.ToList();
        for (int i = 0; i < templist.Count; i++)
        {
            var c = templist[i];
            if (string.IsNullOrEmpty(c.Url))
            {
                c.Url = "http://news.emoney.cn/n_00_0201_" + c.Id + ".shtml";
            }
            DateTime pTime;
            if (c.PTime.HasValue)
            {
                pTime = c.PTime.Value;
            }
            else
            {
                pTime = DateTime.Now;
            }

            sb.AppendLine("  <url><loc>" + c.Url + "</loc><lastmod>" + pTime.ToString("yyyy-MM-dd").ToString() + "</lastmod><changefreq>daily</changefreq><priority>1.0</priority></url>");
        }
        sb.AppendLine("</urlset>");
        str = sb.ToString();
        MemcachedTools.Add(key, str, DateTime.Now.AddMinutes(5));
        return str;
    }

    public List<NewsList> GetListByKeyWord(string[] keyword, int top)
    {
        if (keyword == null)
        {
            return new List<NewsList>();
        }

        List<NewsList> lst = new List<NewsList>();
        foreach (var c in keyword)
        {
            var temp = GetListBy(c);
            lst.AddRange(temp);
            if (lst.Count > top)
            {
                return lst.Take(top).ToList();
            }
            else if (lst.Count == top)
            {
                return lst.ToList();
            }
        }
        return lst.ToList();
    }

    private List<NewsList> GetListBy(string keyword)
    {
        string key = "keyword:" + keyword;
        var json = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(json))
        {
            return JsonBLL.ToObject<List<NewsList>>(json);
        }
        var db = DBManager.GetDB();
        var newsData = (from c in db.News
                        where c.IsEnable == true && c.keyword.Contains(keyword)
                        orderby c.ptime descending
                        select new entity.NewsList { Id = c.id, PTime = c.ptime, Step = c.step, Title = c.title, Url = c.OutsideUrl, KeyWord = c.keyword }
                ).Take(10).ToList();
        json = JsonBLL.ToJson(newsData);
        MemcachedTools.Add(key, json, DateTime.Now.AddMinutes(60));
        
        return newsData;
    }

    public List<NewsList> GetListByStock(string stock, int top)
    {
        top = top == 0 ? 10 : top;
        string key = "GetListByStock_" + stock + "_" + top.ToString();
        var json = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(json))
        {
            return JsonBLL.ToObject<List<NewsList>>(json);
        }
        var db = DBManager.GetDB();
        var tt = from a in db.NewsRelatedStocks
                 from b in db.News
                 where a.NewsId == b.id && b.IsEnable == true && a.Stock == stock && b.ptime <= DateTime.Now
                 orderby b.ptime descending
                 select new entity.NewsList { Id = b.id, PTime = b.ptime, Step = b.step, Title = b.title, Url = b.OutsideUrl, KeyWord = b.keyword };
        var data1 = tt.Take(top).ToList();
        json = JsonBLL.ToJson(data1);
        MemcachedTools.Add(key, json, DateTime.Now.AddHours(2));
        return data1;
    }
}